package com.xxxy.jsq.action.works;

import com.xxxy.jsq.dao.WorksDao;
import com.xxxy.jsq.model.Works;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/updateWorksServlet")
public class updateWorksServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public updateWorksServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码，防止中文乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 实例化作品模型和DAO
        Works model = new Works();
        WorksDao dao = new WorksDao();

        // 获取前端表单数据（与前端name属性对应）
        String worksFlag = request.getParameter("worksFlag");
        String worksName = request.getParameter("worksName");
        String typeId = request.getParameter("typeId");
        String worksOrder = request.getParameter("worksOrder");
        Long worksId = Long.valueOf(request.getParameter("worksId")); // 作品ID（隐藏字段）

        // 设置模型属性（非空判断，避免空指针）
        if (worksFlag != null && !worksFlag.isEmpty()) {
            model.setWorksFlag(worksFlag);
        }
        if (worksName != null && !worksName.isEmpty()) {
            model.setWorksName(worksName);
        }
        if (typeId != null && !typeId.isEmpty()) {
            model.setTypeId(Long.valueOf(typeId));
        }
        if (worksOrder != null && !worksOrder.isEmpty()) {
            model.setWorksOrder(Integer.valueOf(worksOrder));
        }
        // 设置作品ID（必须，用于定位更新对象）
        model.setWorksId(worksId);

        // 调用DAO执行更新操作
        String result = dao.update(model);

        // 输出结果给前端
        PrintWriter out = response.getWriter();
        out.print(result);
        out.flush();
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // POST请求复用GET逻辑
        doGet(request, response);
    }
}
